import axios from "axios";
import {getStore} from "js-utils";
import {Validate} from "js-utils/validate";
import {Message} from "element-ui";
axios.defaults.timeout = 60000;
axios.defaults.baseURL = 'http://59.57.63.157:8199';
// axios.defaults.baseURL = 'http://127.0.0.1:8199';
// 动态设置 baseURL
// const setBaseURL = () => {
//     const serverIp = getStore('guard-ip',1) || '127.0.0.1';
//     axios.defaults.baseURL = `http://${serverIp}:80`;
// };
//
// // 设置初始 baseURL
// setBaseURL();
axios.interceptors.request.use(config => {
    let {url, method} = config;
    method = (method || '').toLowerCase();
    // config.headers['pb-token'] = getToken();
    let name = method === 'get' ? 'params' : 'data';
    if (!config[name]) config[name] = {};
    let data = config[name];
    if (!data.token) data.token = getStore('token',true);
    for (let key in data) {
        if (Validate.isString(data[key])) {
            data[key] = data[key].trim();
        }
    }
    return config;
}, error => {
    return Promise.reject(error);
});
// 导出一个函数，用于在 IP 地址改变时重新设置 baseURL
// export const updateBaseURL = () => {
//     setBaseURL();
// };

axios.interceptors.response.use(res => {
    let {code, msg} = res.data;
    switch (parseInt(code)) {
        case 200:
            return res.data;
        default:
            Message({
                message: msg,
                type: 'error'
            });
            return Promise.reject(res.data);
    }
}, error => {
    let {code, msg = ''} = error;
    switch (code) {
        case 300:
            Message({
                message: msg,
                type: 'warning'
            });
            return Promise.reject(msg);
        default:
            Message({
                message: msg ,
                type: 'error'
            });
            return Promise.reject(msg || error);
    }
});

export default axios;